package cn.huhaoran.yaoyaolingxian.util;

import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.StatusBar;

public class SynchronizeFileUtil {

    public static void synchronizeCurrentFile(Project project, VirtualFile file) {
        // 获取 ActionManager 实例
        ActionManager actionManager = ActionManager.getInstance();

        // 获取 SynchronizeCurrentFileAction
        AnAction synchronizeAction = actionManager.getAction("SynchronizeCurrentFile");

        if (synchronizeAction != null) {
            // 创建一个虚拟的 DataContext
            DataContext dataContext = new DataContext() {
                @Override
                public Object getData(String dataId) {
                    if (PlatformDataKeys.PROJECT.is(dataId)) {
                        return project;
                    }
                    if (PlatformDataKeys.VIRTUAL_FILE.is(dataId)) {
                        return file;
                    }
                    return null;
                }
            };

            // 创建一个虚拟的 AnActionEvent
            AnActionEvent event = AnActionEvent.createFromAnAction(synchronizeAction, null, "", dataContext);

            // 执行该动作
            synchronizeAction.actionPerformed(event);
        } else {
            // 在状态栏显示错误信息
            StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
            if (statusBar != null) {
                statusBar.setInfo("SynchronizeCurrentFile action not found.");
            }
        }
    }
}
